package com.ym.jiujiangeyou.fragment;

import java.io.File;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;

import com.ym.jiujiangeyou.MoreAboutOurs;
import com.ym.jiujiangeyou.MoreFeedBack;
import com.ym.jiujiangeyou.MoreSoftware;
import com.ym.jiujiangeyou.R;

import com.ym.jiujiangeyou.app.MyApplication;
import com.ym.jiujiangeyou.entity.InstallMessage;
import com.ym.jiujiangeyou.parse.ParseGson;
import com.ym.jiujiangeyou.service.AppUpgradeService;
import com.ym.jiujiangeyou.ui.DialogView;
import com.ym.jiujiangeyou.util.ConfigCache;
import com.ym.jiujiangeyou.util.Constants;
import com.ym.jiujiangeyou.util.FileManager;
import com.ym.jiujiangeyou.util.HttpUtil;
import com.ym.jiujiangeyou.util.PackageUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
 /**   
 * @author 叶铭   
 * @email yeming_1001@163.com
 * @version V1.0   
 */
public class MoreFragment extends Fragment implements OnClickListener{

	TextView title_text,more_cache_size_item ;
	RelativeLayout more_update_item,more_ours_item,more_software_item,more_clearcache_item,more_feedback_item,more_follow_item ;
	Handler handler ;
	@SuppressWarnings("unused")
	private InstallMessage installMessage ;
	Dialog dialog ;
	NotificationManager notificationManager ;
	private final static int FLAG_ONE = 1 ;  //启动service
	private final static int FLAG_ZERO = 0 ;//启动activity 
	private String cacheSize = null ;
	File file,file1 ;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View view = inflater.inflate(R.layout.more, null, false) ;
		initResources(view) ;
		
		return view ;
		
	}

	/** 
	* @param title
	* @param intent
	* @param flag  
	* @retur  void 
	* @Description: 自定义弹出框 
	*/
	public void initDialog(int title,final Intent intent,final int flag){
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		View view = inflater.inflate(R.layout.alert_dialog_view, null) ;
		TextView textView = (TextView) view.findViewById(R.id.dialog_text) ;
		textView.setText(title) ;
		RelativeLayout rel_cancel = (RelativeLayout) view.findViewById(R.id.rel_cancel) ;
		RelativeLayout rel_ensure = (RelativeLayout) view.findViewById(R.id.rel_ensure) ;
		final Dialog dialog = new AlertDialog.Builder(getActivity()).create();
		dialog.show();
		dialog.getWindow().setContentView(view);
		rel_cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dialog.dismiss() ;
			}
		}) ;
		rel_ensure.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*Intent intent = new Intent(getActivity(), AppUpgradeService.class) ;
				intent.putExtra("downloadUrl", installMessage.getUrlPath()) ;
				intent.putExtra("fileName", installMessage.getFileName()) ;*/
				
				if(flag == FLAG_ONE){
					getActivity().startService(intent) ;
				}else{
					getActivity().startActivity(intent) ;
				}
				dialog.dismiss() ;
			}
		}) ;
	}
	
	public void initResources(View view){
		
		MyApplication application = (MyApplication) getActivity().getApplication() ;
	//	cacheSize = application.cacheSize ;
		file = application.getCacheDir() ;
		file1 = application.getFilesDir() ;
		title_text = (TextView) view.findViewById(R.id.title_text) ;
	//	more_cache_size_item = (TextView) view.findViewById(R.id.more_cache_size_item) ;
		more_update_item = (RelativeLayout) view.findViewById(R.id.more_update_item) ;
		more_software_item = (RelativeLayout) view.findViewById(R.id.more_software_item) ;
		more_ours_item = (RelativeLayout) view.findViewById(R.id.more_ours_item) ;
		more_clearcache_item = (RelativeLayout) view.findViewById(R.id.more_clearcache_item) ;
		more_feedback_item = (RelativeLayout) view.findViewById(R.id.more_feedback_item) ;
		more_follow_item = (RelativeLayout) view.findViewById(R.id.more_follow_item) ;
		
		title_text.setText("更多") ;
		/*if(cacheSize != null){
			more_cache_size_item.setText(cacheSize) ;
		}*/
		more_update_item.setOnClickListener(this) ;
		more_ours_item.setOnClickListener(this) ;
		more_software_item.setOnClickListener(this) ;
		more_clearcache_item.setOnClickListener(this) ;
		more_feedback_item.setOnClickListener(this) ;
		more_follow_item.setOnClickListener(this) ;
		
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case Constants.HTTP_REQUEST_SUCCESS:
					dialog.dismiss() ;
					installMessage = (InstallMessage) msg.obj ;
					if(!isAlready(installMessage.getFileName())){
						PackageUtils packageUtils = new PackageUtils(getActivity()) ;
						if(packageUtils.isUpgrade(packageUtils.getVersionCode(), installMessage.getVersionCode())){
						//	Toast.makeText(getActivity(), "行版本", 0).show() ;
							//builder.create().show() ;
							Intent intent = new Intent(getActivity(), AppUpgradeService.class) ;
							intent.putExtra("downloadUrl", installMessage.getUrlPath()) ;
							intent.putExtra("fileName", installMessage.getFileName()) ;
							initDialog(R.string.alert_update_text,intent,FLAG_ONE) ;
						}
					}else{
						Uri uri = Uri.fromFile(new File(FileManager.getSaveApkPath() + "/"
								+ installMessage.getFileName()));
				        Intent intent1 = new Intent(Intent.ACTION_VIEW);
				        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				        intent1.setDataAndType(uri, "application/vnd.android.package-archive");
				        initDialog(R.string.alert_installed_text,intent1,FLAG_ZERO) ;
					}
					
					break;
				case Constants.HTTP_REQUEST_ERROR:
					dialog.dismiss() ;
					Toast.makeText(getActivity(), R.string.check_network_please, 0).show() ;
					break ;
				case Constants.CLEAR_CACHE_SUCCESS:
					/*if(cacheSize != null){
						more_cache_size_item.setText(cacheSize) ;
					}*/
					Toast.makeText(getActivity(), R.string.more_clear_cache_success, 0).show() ;
					break ;
				default:
					break;
				}
				
			}
		} ;
	}
	
	/** 
	* @param fileName
	* @return  
	* @retur  boolean 
	* @Description: 判断安装文件是否存在
	*/
	public boolean isAlready(String fileName){
		boolean flag = false ;
		File fileDir = new File(FileManager.getSaveApkPath()) ;
		if (fileDir.exists()) {
			File file = new File(fileDir.getPath() + "/"
					+ fileName);
			if (file.exists() && file.isFile()) {
				flag = true ;
			}
		}
		return flag ;
	}
	
	/** 
	*   
	* @retur  void 
	* @Description: 关注微博 
	*/
	private void attention(){
		Platform plat = ShareSDK.getPlatform(getActivity(), SinaWeibo.NAME);
		plat.setPlatformActionListener(new PlatformActionListener() {
			
			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show() ;
			}
			
			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "success", Toast.LENGTH_SHORT).show() ;
			}
			
			@Override
			public void onCancel(Platform arg0, int arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "cancel", Toast.LENGTH_SHORT).show() ;
			}
		}) ;
		plat.followFriend("2614932589");//2881812642
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.more_update_item :
			dialog = DialogView.popDialog(getActivity(), R.string.ischecking) ;
			dialog.show() ;
			//Toast.makeText(getActivity(), "好玩不好玩", 0).show() ;
			new Thread(new Runnable() {
				Message message = new Message() ;
				InstallMessage installMessage = null ;
				String s ;
				@Override
				public void run() {
					// TODO Auto-generated method stub
					s = HttpUtil.httpGet(Constants.GET_UPDATE_INFO_URL) ;
			//		s = HttpUtil.get(Constants.GET_UPDATE_INFO_URL) ;
					System.out.println("----------s---------"+s);
					installMessage = ParseGson.parseInstallMessage(s) ;
					if(installMessage != null){
						message.what = Constants.HTTP_REQUEST_SUCCESS ;
						message.obj = installMessage ;
						System.out.println("-------------------"+installMessage.toString());
					}else{
						message.what = Constants.HTTP_REQUEST_ERROR ;
					}
					handler.sendMessage(message) ;
				}
			}).start() ;
			break;
		case R.id.more_ours_item:
			Intent intent = new Intent(getActivity(), MoreAboutOurs.class) ;
			getActivity().startActivity(intent) ;
			break ;
		case R.id.more_software_item:
			Intent intent1 = new Intent(getActivity(), MoreSoftware.class) ;
			getActivity().startActivity(intent1) ;
			break ;
		case R.id.more_clearcache_item:
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Message message = new Message() ;
				//	FileManager.clearImageCache() ;
				//	FileManager.clearApkFile() ;
					MyApplication application = (MyApplication) getActivity().getApplication() ;
				//	FileManager.clearDirs() ;
					ConfigCache.clearCache(file) ;
					ConfigCache.clearCache(file1) ;
					FileManager.clearImageCache() ;
				//	application.clearAppCache() ;
				//	cacheSize = application.getCacheSize() ;
					message.what = Constants.CLEAR_CACHE_SUCCESS ;
				//	message.obj = cacheSize ;
					handler.sendMessage(message) ;
				}
			}).start() ;
			
			break ;
		case R.id.more_feedback_item:
			Intent intent2 = new Intent(getActivity(), MoreFeedBack.class) ;
			getActivity().startActivity(intent2) ;
			break ;
		case R.id.more_follow_item:
			attention() ;
			break ;
		default:
			break;
		}
	}
}
